<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Promise 异步编程应用场景</title>
</head>
<body>
  <button onclick="userLogin()">用户登录</button>
</body>
<script src="./js/jquery.min.js"></script>
<script>
  function userLogin() {
    // 1. 使用 Promise进行异步操作()
    // 127.0.0.1:3000/user/login
    // 127.0.0.1:3000/user/friends
    /*
    $.ajax({// 127.0.0.1:3000/user/login
      type: 'POST',
      url: 'http://127.0.0.1:3000/user/login',
      data: {uname: 'Tiger', upwd: '123456'},
      dataType: 'json',
      success: function (data) {
        console.log(data);
        $.ajax({})
      },
      error: function (xhr, type) {
        console.log(xhr, type);
      }
    });
    */ 
    let promiseA = new Promise((resolve, reject) => {
      // 2. 发第一个请求127.0.0.1:3000/user/login
      $.ajax({
        type: 'POST',
        url: 'http://127.0.0.1:3000/user/login',
        data: {uname: 'Jack', upwd: '123456'},
        dataType: 'json',
        success: function(data) {
          console.log('第一个请求返回的数据:', data);
          // 在成功执行的地方进行 状态传递
          resolve({data:data});
        },
        error: function(xhr, type) {
          console.log(xhr, type);
          // 传递失败的状态
          reject({msg: 'network error', type: type});
        }
      });
    });

    // let promiseB = new Promise((resolve, reject) => {
    //   // 3.第二个请求 127.0.0.1:3000/user/friends
    //   $.ajax({
    //     type: 'GET',
    //     url: 'http://127.0.0.1:3000/user/friends'
    //   });
    // });

    promiseA.then(data => {
      console.log('then data:', data.data);
      if (data.data.code == 200) {
        let token = data.data.token;
        if (token) {
          // 发第二个请求
          // 字符串的方式
          let url_string = `http://127.0.0.1:3000/user/friends?token=${token}`;
          console.log(url_string);
          $.ajax({
            type: 'GET',
            url: url_string,
            dataType: 'json',
            success: function(data){
              console.log('第二次请求的结果:', data);
            },
            error: function(xhr, type) {
              console.log(xhr,type);
            }
          });
        }
      } else {
        console.log('code is not 200');
      }
      
    }).catch(err => {
      console.log(err);
    });

  }
</script>
</html>